

#import "NSMSMSButton.h"

@interface NSMSMSButton ()
@property (nonatomic) NSTimeInterval currentInterval;
@property (nonatomic, strong) GCDTimer *timer;
@property (nonatomic, copy) NSString *normalTitle;
@end

@implementation NSMSMSButton

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self didInitialize];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (CGRectIsEmpty(frame)) {
        frame = CGRectMake(0, 0, 87, 27);
    }
    self = [super initWithFrame:frame];
    if (self) {
        [self didInitialize];
    }
    return self;
}

- (void)didInitialize {
    self.groupTag = 0;
    self.countdownInterval = 60.f;
    self.countdownPolicy = NSMSMSCountdownUntilDone;
    self.normalTitle = @"获取验证码";
    self.normalTitleColor = UIColor.whiteColor;
    self.disabledTitleColor = UIColor.lightGrayColor;
    self.normalBackgroundColor = UIColor.blackColor;
    self.disabledBackgroundColor = UIColor.groupTableViewBackgroundColor;
    self.cornerRadius = 3;
    
    self.userInteractionEnabled = NO;
    [self addTarget:self action:@selector(onClickBtn) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - setter/getter
- (NSTimeInterval)remainingInterval {
    NSTimeInterval interval = 0;
    NSString *key = FormatString(@"sms_group_%zd", self.groupTag);
    switch (self.countdownPolicy) {
        case NSMSMSCountdownDoneElseRestart:
        case NSMSMSCountdownUntilDone:
        {
            NSTimeInterval local;
            id lastTime;
            if (self.countdownPolicy == NSMSMSCountdownDoneElseRestart)
                lastTime = [_cacheManager.smsCache.memoryCache objectForKey:key];
            else if (self.countdownPolicy == NSMSMSCountdownUntilDone)
                lastTime = [_cacheManager.smsCache.diskCache objectForKey:key];
            
            if (lastTime)
                local = [lastTime doubleValue];
            else
                local = NSTimeIntervalSince1970;
            
            interval = MAX(self.countdownInterval - (time(NULL) - local), 0);
        }
            break;
        default:
            break;
    }
    return interval;
}

- (GCDTimer *)timer {
    if (!_timer) {
        @nsm_weak(self)
        _timer = GCDTimer.new.queue(dispatch_get_main_queue())
        .parameters(0, 1)
        .eventHandler(^{
            @nsm_strong(self)
            [self countDown];
        });
    }
    return _timer;
}

- (void)reloadAndUpdate {
    self.titleLabel.font = CustomFont(13);
    [self setTitleColor:self.normalTitleColor forState:UIControlStateNormal];
    [self setTitleColor:self.disabledTitleColor forState:UIControlStateDisabled];
    [self setBackgroundImage:[UIImage imageWithColor:self.normalBackgroundColor] forState:UIControlStateNormal];
    [self setBackgroundImage:[UIImage imageWithColor:self.disabledBackgroundColor] forState:UIControlStateDisabled];
    self.layer.masksToBounds = YES;
    self.layer.cornerRadius = self.cornerRadius;
    
    self.userInteractionEnabled = YES;
    
    // 检查当前倒计时
    self.currentInterval = [self remainingInterval];
    // 直接启动定时器检测状态
    self.timer.resume();
}

- (void)resetLocalTime {
    // 记录的是开始倒计时的时间
    time_t lastTime = time(NULL);
    
    // 更新策略NSMSMSCountdownUntilDone
    NSString *key = FormatString(@"sms_group_%zd", self.groupTag);
    [_cacheManager.smsCache.diskCache setObject:@(lastTime) forKey:key];
    
    // 更新策略NSMSMSCountdownDoneElseRestart
    [_cacheManager.smsCache.memoryCache setObject:@(lastTime) forKey:key];
}

#pragma mark - 倒计时
- (void)countDown {
    _currentInterval--;
    NSString *title;
    BOOL enabled = NO;
    if (_currentInterval <= 0) {
        _currentInterval = 0;
        title = self.normalTitle;
        enabled = YES;
        self.timer.pause();
    } else {
        enabled = NO;
        title = FormatString(@"%ld (s)",(long)_currentInterval);
    }
    self.enabled = enabled;
    [self setTitle:title forState:UIControlStateNormal];
}

#pragma mark - action
- (void)onClickBtn {
    [self setTitle:@"" forState:UIControlStateNormal];
    self.userInteractionEnabled = NO;
    self.isLoading = YES;
    
    @nsm_weak(self)
    // 没有实现点击方法
    if (!self.onActionHandler) {
        @nsm_strong(self)
        [self setTitle:self.normalTitle forState:UIControlStateNormal];
        self.userInteractionEnabled = YES;
        self.isLoading = NO;
        return;
    }
    
    // 实现了点击方法
    self.onActionHandler(^(BOOL success) {
        @nsm_strong(self)
        [self setTitle:self.normalTitle forState:UIControlStateNormal];
        self.userInteractionEnabled = YES;
        self.isLoading = NO;
        if (success) {
            self.enabled = NO;
            self.currentInterval = self.countdownInterval;
            self.timer.resume();
            // 重置本地记录
            [self resetLocalTime];
        }
    });
}

@end
